<template>
  <BasicDrawer
    :destroyOnClose="true"
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="state.title"
    width="670px"
    :maskClosable="false"
    :headerStyle="{ borderBottom: 0 }"
  >
    <template #footer>
      <a-flex gap="middle" align="center" justify="center" style="height: 100%">
        <div style="color: #6d414c"
          ><span>合计：</span>¥<span style="font-weight: 500; font-size: 20px">{{
            formData.payablePrice
          }}</span></div
        >
        <a-button danger @click="closeDrawer()">取消</a-button>
        <!-- <a-button danger @click="onSaveOrder">挂单</a-button> -->
        <a-button type="primary" @click="onSave()">提交</a-button>
      </a-flex>
    </template>

    <card-head :item="record" />

    <div style="padding-top: 32px">
      <BasicForm @register="registerForm1">
        <template #title1>
          <div style="font-weight: 500; font-size: 16px; color: #333333; padding-left: 32px">
            续充信息
          </div>
        </template>

        <template #title2>
          <div style="font-weight: 500; font-size: 16px; color: #333333; padding-left: 32px">
            其他信息
          </div>
        </template>
      </BasicForm>
    </div>
  </BasicDrawer>

  <CardRechargePayment @register="registerPayment" @success="onSuccess"></CardRechargePayment>
</template>
<script setup>
  import { inject, provide, reactive, ref } from 'vue';
  import { BasicDrawer, useDrawerInner, useDrawer } from '@/components/Drawer';
  import dayjs from 'dayjs';
  import { useMessage } from '@/hooks/web/useMessage';
  import CardHead from '@/views/member/card-head.vue';
  import { PAGE, POST } from '@/api/http.js';
  import { BasicForm, useForm } from '@/components/Form';
  import { getUserInfo } from '@/utils/auth';
  import { exist } from '@/api/util.js';
  import { savePendingOrder } from '../cashier/cart';
  import CardRechargePayment from './card-recharge-payment.vue';

  const [registerPayment, { openDrawer: paymentDrawer }] = useDrawer();

  const emit = defineEmits(['complete']);

  const state = reactive({});
  const record = ref({});
  const beauticianList = ref([]);

  const formData = reactive({
    payablePrice: 0,
  });

  let masterOrderSns = '';

  const { createMessage } = useMessage();

  const [registerDrawer, { setDrawerProps, closeDrawer, changeLoading }] = useDrawerInner(
    async ({ memberCode, record: item, masterOrderSn }) => {
      masterOrderSns = masterOrderSn;
      record.value = item;
      Object.assign(state, { title: '卡续充', memberCode });
      await loadData();

      form1.setFieldsValue({ addTime: dayjs() });
    },
  );

  const [registerForm1, form1] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24, style: { paddingRight: '36px' } },

    schemas: [
      {
        component: 'Render',
        slot: 'title1',
      },

      {
        label: '充值金额',
        field: 'rechargePrice',
        required: true,
        component: 'InputNumber',
        componentProps: {
          min: 0,
          max: 9999999,
          precision: 2,
          addonAfter: '元',
          onChange(target) {
            const value = parseFloat(target || 0) - (form1.getFieldsValue()?.saleDiscount || 0);
            formData.payablePrice = Math.max(0, value);
          },
        },
        colProps: {
          span: 16,
        },
      },

      {
        label: '销售人员',
        field: 'employeesCodeList',
        required: true,
        component: 'Select',
        componentProps: {
          placeholder: '选择美容师',
          mode: 'multiple',
          showArrow: true,
          options: beauticianList,
          showSearch: false,
        },
        colProps: {
          span: 16,
        },
      },

      {
        component: 'Render',
        slot: 'title2',
      },

      {
        label: '下单时间',
        field: 'addTime',
        required: true,
        component: 'DatePicker',
        componentProps: {
          showTime: true,
          placeholder: '请选择下单时间',
          valueFormat: 'YYYY-MM-DD HH:mm:ss',
          format: 'YYYY-MM-DD HH:mm:ss',
          disabledDate: (value) => !dayjs(value).isSameOrBefore(dayjs()),
        },
        colProps: {
          span: 16,
        },
      },

      {
        label: '优惠金额',
        field: 'saleDiscount',
        required: false,
        component: 'InputNumber',
        componentProps: {
          min: 0,
          max: 9999999,
          precision: 2,
          addonAfter: '元',
          onChange(target) {
            const value = (form1.getFieldsValue()?.rechargePrice || 0) - parseFloat(target || 0);
            formData.payablePrice = Math.max(0, value);
          },
        },
        colProps: {
          span: 16,
        },
      },

      {
        label: '备注',
        field: 'remarks',
        required: false,
        component: 'InputTextArea',
        componentProps: {
          showCount: true,
          maxlength: 200,
        },
      },
    ],
    showActionButtonGroup: false,
  });

  // const { onSavePendingOrder } = inject('onSavePendingOrder');
  // function onSaveOrder () {
  //   onSavePendingOrder()
  // }

  async function loadData() {
    beauticianList.value =
      (await PAGE('/membership/getEmployeeInfoBeanPages')({
        status: 1,
        currentPage: 1,
        pageSize: 999999,
      }).then((result) =>
        result?.list?.map((o) => ({
          ...o,
          value: o.employeeCode,
          label: o.realName,
        })),
      )) ?? [];
  }

  const onSuccess = () => {
    emit('complete');
  };

  async function onSave() {
    await form1.validate();
    const formData = form1.getFieldsValue();
    console.log(formData);
    console.log(record, 'recordrecordrecord', beauticianList);

    if (formData.rechargePrice < formData.saleDiscount) {
      return createMessage.error('优惠金额不能大于充值金额');
    }

    paymentDrawer(true, {
      masterOrderSn: masterOrderSns,
      formData,
      beauticianList: beauticianList.value,
      memberCode: state.memberCode,
      record: record.value,
      closeFtherDrawer: closeDrawer,
    });

    // const data = {...formData};
    // let {rechargePrice, employeesCodeList, addTime, saleDiscount, remarks} = data;
    // saleDiscount ||= 0;

    // employeesCodeList = beauticianList.value?.filter(o => exist(o.value, employeesCodeList))?.map(o => ({
    //   employeeCode: o.value,
    //   employeeName: o.label
    // })) ?? [];

    // try {
    //   changeLoading(true);

    //   const {memberCode} = state;
    //   const {cardNo, batchNo, cardType} = record.value;
    //   const {employeeCode: cashierCode} = getUserInfo()?.resultBean ?? {};

    //   await POST('/cashier/createCardRechangeOrder', {
    //     memberCode, cardType, cashierCode, cardNo, batchNo,
    //     referer: 'PC端', sourceCode: '20', cashPayCode: 'cash',
    //     rechargePrice, employeesCodeList, addTime, saleDiscount, remarks
    //   });

    //   createMessage.success('充值已完成');
    //   emit('complete');
    //   closeDrawer();
    // } finally {
    //   changeLoading(false);
    // }
  }
</script>

<style lang="less" scoped></style>
